package com.perfma.xtest.tool;

import com.google.common.collect.Lists;
import com.perfma.xtest.tool.word.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author: junhui.si
 * @date: 2022-01-10 15:49
 **/
public class JmxFileDemo {

    public static void main(String[] args) {
        String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<jmeterTestPlan version=\"1.2\" properties=\"5.0\" jmeter=\"5.4\">\n" +
                "  <hashTree>\n" +
                "    <TestPlan guiclass=\"TestPlanGui\" testclass=\"TestPlan\" testname=\"各种文件\" enabled=\"true\">\n" +
                "      <stringProp name=\"TestPlan.comments\"></stringProp>\n" +
                "      <boolProp name=\"TestPlan.functional_mode\">false</boolProp>\n" +
                "      <boolProp name=\"TestPlan.tearDown_on_shutdown\">true</boolProp>\n" +
                "      <boolProp name=\"TestPlan.serialize_threadgroups\">false</boolProp>\n" +
                "      <elementProp name=\"TestPlan.user_defined_variables\" elementType=\"Arguments\" guiclass=\"ArgumentsPanel\" testclass=\"Arguments\" testname=\"用户定义的变量\" enabled=\"true\">\n" +
                "        <collectionProp name=\"Arguments.arguments\"/>\n" +
                "      </elementProp>\n" +
                "      <stringProp name=\"TestPlan.user_define_classpath\"></stringProp>\n" +
                "    </TestPlan>\n" +
                "    <hashTree>\n" +
                "      <ThreadGroup guiclass=\"ThreadGroupGui\" testclass=\"ThreadGroup\" testname=\"线程组\" enabled=\"true\">\n" +
                "        <stringProp name=\"ThreadGroup.on_sample_error\">continue</stringProp>\n" +
                "        <elementProp name=\"ThreadGroup.main_controller\" elementType=\"LoopController\" guiclass=\"LoopControlPanel\" testclass=\"LoopController\" testname=\"循环控制器\" enabled=\"true\">\n" +
                "          <boolProp name=\"LoopController.continue_forever\">false</boolProp>\n" +
                "          <stringProp name=\"LoopController.loops\">1</stringProp>\n" +
                "        </elementProp>\n" +
                "        <stringProp name=\"ThreadGroup.num_threads\">1</stringProp>\n" +
                "        <stringProp name=\"ThreadGroup.ramp_time\">1</stringProp>\n" +
                "        <boolProp name=\"ThreadGroup.scheduler\">false</boolProp>\n" +
                "        <stringProp name=\"ThreadGroup.duration\"></stringProp>\n" +
                "        <stringProp name=\"ThreadGroup.delay\"></stringProp>\n" +
                "        <boolProp name=\"ThreadGroup.same_user_on_next_iteration\">true</boolProp>\n" +
                "      </ThreadGroup>\n" +
                "      <hashTree>\n" +
                "        <TransactionController guiclass=\"TransactionControllerGui\" testclass=\"TransactionController\" testname=\"事务控制器\" enabled=\"true\">\n" +
                "          <boolProp name=\"TransactionController.includeTimers\">false</boolProp>\n" +
                "          <boolProp name=\"TransactionController.parent\">false</boolProp>\n" +
                "        </TransactionController>\n" +
                "        <hashTree>\n" +
                "          <HTTPSamplerProxy guiclass=\"HttpTestSampleGui\" testclass=\"HTTPSamplerProxy\" testname=\"HTTP请求\" enabled=\"false\">\n" +
                "            <elementProp name=\"HTTPsampler.Files\" elementType=\"HTTPFileArgs\">\n" +
                "              <collectionProp name=\"HTTPFileArgs.files\">\n" +
                "                <elementProp name=\"/Users/sijunhui/Downloads/1-jmeter/1111.jmx\" elementType=\"HTTPFileArg\">\n" +
                "                  <stringProp name=\"File.path\">/Users/sijunhui/Downloads/1-jmeter/1111.jmx</stringProp>\n" +
                "                  <stringProp name=\"File.paramname\"></stringProp>\n" +
                "                  <stringProp name=\"File.mimetype\"></stringProp>\n" +
                "                </elementProp>\n" +
                "                <elementProp name=\"/Users/sijunhui/Downloads/1-jmeter/变量.jmx\" elementType=\"HTTPFileArg\">\n" +
                "                  <stringProp name=\"File.path\">/Users/sijunhui/Downloads/1-jmeter/变量.jmx</stringProp>\n" +
                "                  <stringProp name=\"File.paramname\"></stringProp>\n" +
                "                  <stringProp name=\"File.mimetype\"></stringProp>\n" +
                "                </elementProp>\n" +
                "              </collectionProp>\n" +
                "            </elementProp>\n" +
                "            <elementProp name=\"HTTPsampler.Arguments\" elementType=\"Arguments\" guiclass=\"HTTPArgumentsPanel\" testclass=\"Arguments\" testname=\"用户定义的变量\" enabled=\"true\">\n" +
                "              <collectionProp name=\"Arguments.arguments\"/>\n" +
                "            </elementProp>\n" +
                "            <stringProp name=\"HTTPSampler.domain\"></stringProp>\n" +
                "            <stringProp name=\"HTTPSampler.port\"></stringProp>\n" +
                "            <stringProp name=\"HTTPSampler.protocol\"></stringProp>\n" +
                "            <stringProp name=\"HTTPSampler.contentEncoding\"></stringProp>\n" +
                "            <stringProp name=\"HTTPSampler.path\"></stringProp>\n" +
                "            <stringProp name=\"HTTPSampler.method\">GET</stringProp>\n" +
                "            <boolProp name=\"HTTPSampler.follow_redirects\">true</boolProp>\n" +
                "            <boolProp name=\"HTTPSampler.auto_redirects\">false</boolProp>\n" +
                "            <boolProp name=\"HTTPSampler.use_keepalive\">true</boolProp>\n" +
                "            <boolProp name=\"HTTPSampler.DO_MULTIPART_POST\">false</boolProp>\n" +
                "            <stringProp name=\"HTTPSampler.embedded_url_re\"></stringProp>\n" +
                "            <stringProp name=\"HTTPSampler.connect_timeout\"></stringProp>\n" +
                "            <stringProp name=\"HTTPSampler.response_timeout\"></stringProp>\n" +
                "          </HTTPSamplerProxy>\n" +
                "          <hashTree/>\n" +
                "        </hashTree>\n" +
                "        <CSVDataSet guiclass=\"TestBeanGUI\" testclass=\"CSVDataSet\" testname=\"CSV 数据文件设置\" enabled=\"true\">\n" +
                "          <stringProp name=\"delimiter\">,</stringProp>\n" +
                "          <stringProp name=\"fileEncoding\"></stringProp>\n" +
                "          <stringProp name=\"filename\">/Users/sijunhui/Downloads/1-jmeter/不同线程组-相同流量控制器.jmx</stringProp>\n" +
                "          <boolProp name=\"ignoreFirstLine\">false</boolProp>\n" +
                "          <boolProp name=\"quotedData\">false</boolProp>\n" +
                "          <boolProp name=\"recycle\">true</boolProp>\n" +
                "          <stringProp name=\"shareMode\">shareMode.all</stringProp>\n" +
                "          <boolProp name=\"stopThread\">false</boolProp>\n" +
                "          <stringProp name=\"variableNames\"></stringProp>\n" +
                "        </CSVDataSet>\n" +
                "        <hashTree/>\n" +
                "      </hashTree>\n" +
                "    </hashTree>\n" +
                "  </hashTree>\n" +
                "</jmeterTestPlan>\n";
        System.out.println(getAllEnableFileName(s));
    }

    public static List<String> getAllEnableFileName(String content) {

        List<String> allFiles = Lists.newArrayList();
        try {
            SAXReader reader = new SAXReader();
            InputStream in_withcode = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));

            Document document = reader.read(in_withcode);
            Element root = document.getRootElement();

            // 查找所有csv data set
            List<Element> csvElement = root.selectNodes("//*[contains(name(),'CSVDataSet')]");
            for (Element element : csvElement) {
                String enable = element.attributeValue("enabled");
                if (!Boolean.TRUE.toString().equals(enable)) {
                    continue;
                }
                List filePathNodes = element.selectNodes(".//*[@name='filename']");
                getFiles(filePathNodes, allFiles);
            }

            // 查找所有http请求
            List<Element> httpElement = root.selectNodes("//*[contains(name(),'HTTPSamplerProxy')]");
            for (Element element : httpElement) {
                String enable = element.attributeValue("enabled");
                if (!Boolean.TRUE.toString().equals(enable)) {
                    continue;
                }
                List filePathNodes = element.selectNodes(".//*[@name='File.path']");
                getFiles(filePathNodes, allFiles);
            }
            //先检查http请求里的数据参数File.path
//            List filePaths = element.selectNodes("//*[@name='File.path']");
//            List csvDataPath = element.selectNodes("//*[@name='filename']");
//            List t2DataPath = element.selectNodes("//*[@name='T2Sample.cert.filepath']");
//
//            getFiles(filePaths, allFiles);
//            getFiles(csvDataPath, allFiles);
//            getFiles(t2DataPath, allFiles);
        } catch (Exception ex) {
        }

        return allFiles;
    }

    private static void getFiles(List nodes, List<String> allFiles) {

        if (CollectionUtil.isNotEmpty(nodes)) {
            for (Object object : nodes) {
                Element pathElement = (Element) object;
                String pathContent = pathElement.getText();
                pathContent = pathContent.replace("\\", "/");
                String fileName = StringUtils.substringAfterLast(pathContent, File.separator);
                if (StringUtils.isNotEmpty(fileName)) {
                    allFiles.add(fileName);
                }
            }
        }
    }
}
